{include file="common/header"/}
<style type="text/css">
    .layui-table-cell {
        overflow: visible;
        height: auto;
        vertical-align: middle; /* 单元格内容垂直居中 */
    }
    .son {
        height: 20px;
    }
    .child-row { /* 子行样式 */
        background: #f8f8f8;
    }
</style>
<div class="lemo-container">
    <div class="lemo-main">
        <div class="admin-main layui-anim layui-anim-upbit">
            <fieldset class="layui-elem-field layui-field-title">
                <legend>客户报价表</legend>
                <blockquote class="layui-elem-quote">
                    <input type="hidden" id="id" value="{$id}">
                    <!-- <div class="layui-inline">
                        
                        <input type="text" id='keys' name="keys" lay-verify="required" placeholder="{:lang('pleaseEnter')}" autocomplete="off" class="layui-input">
                    </div>
                    <a href="javascript:;" class="layui-btn data-add-btn layui-btn-sm" lay-submit="" lay-filter="search" id="search">{:lang('search')}</a> -->
                    <a data-href='{:url("addCustomer")}' href="javascript:;" class="layui-btn layui-btn-sm layui-btn-warm addid">{:lang('add')}</a>
                    <button class="layui-btn layui-btn-sm layui-btn-normal" id="importExcel">导入Excel</button>
                </blockquote>
            </fieldset>
            <table class="layui-table" id="list" lay-filter="list"></table>
        </div>
    </div>
</div>

<script type="text/html" id="action">
    <a data-href="{:url('addSku')}?id={{d.id}}" class="layui-btn layui-btn-xs" lay-event="edit">添加 sku</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" data-href="{:url('productDel')}" lay-event="del">删除</a>
</script>

<script type="text/html" id="imgurl">
    <img class="layui-upload-img" src="{{d.avatar}}" width="80px" height="80px">
</script>

{include file="common/footer"/}
<script>

layui.config({
        base: "/static/admin/js/",
        version: true
    }).extend({
        Admin: 'Admin'
    }).use(['form', 'table', 'jquery', 'Admin', 'upload'], function () {
        var table = layui.table,
            $ = layui.jquery,
            layer = layui.layer;
            upload = layui.upload;
        table.render({
            elem: '#list',
            url: '{:url("customer")}',
            method: 'post',
            where: {
                id: $('#id').val(),
            },
            cols: [[
                {field: 'id', title: 'ID', width: 80},
                {field: 'physical_pic', title: '实物图', width: 100, toolbar: '#imgurl0'},
                {field: 'product_name', title: '商品名称', width: 120},
                {field: 'specifications_pic', title: '商品规格图', width: 100, toolbar: '#imgurl1'},
                {field: 'attribute', title: '商品属性', width: 60},
                {title: '数量', width: 60},  
                {title: '单价', width: 60},  
                {title: '运费', width: 60},  
                {title: '总额', width: 90},  
                {field: 'quotation_pic', title: '报价截图', width: 100, toolbar: '#imgurl2'},
                {field: 'price_adjustment_date', title: '调价日期', width: 100},
                {field: 'purchasing_cost', title: '拿货成本', width: 80},
                {field: 'freight_remarks', title: '运费备注', width: 80},
                {field: 'manufactor', title: '厂家', width: 80},
                {field: 'product_type', title: '产品类型', width: 80},
                {field: 'consumables', title: '耗材', width: 80},
                {field: 'artificial', title: '人工', width: 80},
                {field: 'cargo_damage', title: '货损', width: 80},
                {title: '共计', width: 80},  
                {title: '状态', width: 80, toolbar: '#action', align: "center"},
                {title: '操作', width: 120, toolbar: '#action', align: "center"},
                {field: 'notes', title: '备注', width: 80},
            ]],
            page: true,
            limit: 15,
            done: function(res) {  
                var $tbody = $(this.elem).next('.layui-table-view').find('.layui-table-body tbody');
                var data = res.data;  

                // 清空原有行（Layui默认会渲染所有字段，需手动覆盖）

                function get_type(type) {
                    var str = '';
                    switch (type) {
                        case 0: 
                            break;
                        case 1:
                            str = '自营';
                            break;
                        case 2:
                            str = '代发';
                            break;
                    }
                    return str;
                }

                $tbody.empty();

                // 遍历主数据，插入主行+子行
                data.forEach((mainRow, mainIndex) => {
                    // 计算主行需要合并的行数（sku数量 + 主行自己）
                    var rowSpan = mainRow.sku.length > 0 ? mainRow.sku.length : 1;

                    // 插入主行（前7列合并rowspan）
                    var batchTd = mainRow.sku.length > 0? `<td  data-field="id" data-key="1-0-5" class="">
                                <div class=" laytable-cell-1-0-5 son">${mainRow.sku[0].num}${mainRow.unit}</div>
                            </td>
                            <td  data-field="id" data-key="1-0-6" class="">
                                <div class=" laytable-cell-1-0-6 son">${mainRow.sku[0].price}</div>
                            </td>
                            <td data-field="id" data-key="1-0-7" class="">
                                <div class=" laytable-cell-1-0-7 son">${mainRow.sku[0].shipping_fee}</div>
                            </td>
                            <td data-field="id" data-key="1-0-8" class="">
                                <div class=" laytable-cell-1-0-8 son">${mainRow.sku[0].num}${mainRow.unit}/ ${Number(mainRow.sku[0].num) * Number(mainRow.sku[0].price) + Number(mainRow.sku[0].shipping_fee)}</div>
                            </td>
                            `: `<td colspan="4" width="244px">
                                
                            </td>`;
                    var statusStr = mainRow.status?` <a class="layui-btn  layui-btn-xs layui-btn-disabled" >已审核</a>`:`<a data-href="/admin/maichen.Supply/changeStatus.html?id=${mainRow.id}" class="layui-btn layui-btn-xs" lay-event="edit">审核</a>`;
                    var mainTr = `
                        <tr data-index="${mainIndex}">
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-0" class="">
                                <div class="layui-table-cell laytable-cell-1-0-0">${mainRow.id}</div>
                            </td>
                            
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-1" class="">
                                <div class="layui-table-cell laytable-cell-1-0-1"><a data-href="${mainRow.physical_pic}" data-area="['400px', '300px']" lay-event="look"><img src="${mainRow.physical_pic}" width="80px"></a></div>
                            </td>
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-2" class="">
                                <div class="layui-table-cell laytable-cell-1-0-2">${mainRow.product_name}</div>
                            </td>
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-3" class="">
                                <div class="layui-table-cell laytable-cell-1-0-3"><a data-href="${mainRow.specifications_pic}" data-area="['400px', '300px']" lay-event="look"><img src="${mainRow.specifications_pic}" width="80px"></a></div>
                            </td>
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-4" class="">
                                <div class="layui-table-cell laytable-cell-1-0-4">${mainRow.attribute}</div>
                            </td>
                            ${batchTd}
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-9" class="">
                                <div class="layui-table-cell laytable-cell-1-0-9"><a data-href="${mainRow.quotation_pic}" data-area="['400px', '300px']" lay-event="look"><img src="${mainRow.quotation_pic}" width="80px"></a></div>
                            </td>
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-10" class="">
                                <div class="layui-table-cell laytable-cell-1-0-10">${mainRow.price_adjustment_date}</div>
                            </td>
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-11" class="">
                                <div class="layui-table-cell laytable-cell-1-0-11">${mainRow.purchasing_cost}</div>
                            </td>
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-12" class="">
                                <div class="layui-table-cell laytable-cell-1-0-12">${mainRow.freight_remarks}</div>
                            </td>
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-13" class="">
                                <div class="layui-table-cell laytable-cell-1-0-13">${mainRow.manufactor}</div>
                            </td>
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-14" class="">
                                <div class="layui-table-cell laytable-cell-1-0-14">${get_type(mainRow.product_type)}</div>
                            </td>
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-15" class="">
                                <div class="layui-table-cell laytable-cell-1-0-15">${mainRow.consumables}</div>
                            </td>
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-16" class="">
                                <div class="layui-table-cell laytable-cell-1-0-16">${mainRow.artificial}</div>
                            </td>
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-17" class="">
                                <div class="layui-table-cell laytable-cell-1-0-17">${mainRow.cargo_damage}</div>
                            </td>
                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-18" class="">
                                <div class="layui-table-cell laytable-cell-1-0-18">${Number(mainRow.cargo_damage) + Number(mainRow.consumables) + Number(mainRow.artificial) + Number(mainRow.cargo_damage) }</div>
                            </td>

                            <td rowspan="${rowSpan}" data-field="6" data-key="1-0-19" align="center" data-off="true" class="layui-table-col-special">
                                <div class="layui-table-cell laytable-cell-1-0-19"> 
                              ${statusStr}
                                </div>
                            </td>

                            <td rowspan="${rowSpan}" data-field="6" data-key="1-0-16" align="center" data-off="true" class="layui-table-col-special">
                                <div class="layui-table-cell laytable-cell-1-0-16"> 
                                    <a data-href="/admin/maichen.Supply/addSku.html?id=${mainRow.id}" class="layui-btn layui-btn-xs" lay-event="edit">添加sku</a> <br>
                                    <a data-href="/admin/maichen.Supply/editCustomer.html?id=${mainRow.id}" class="layui-btn layui-btn-xs" lay-event="edit">编辑</a> <br>
                                    <a  class="layui-btn layui-btn-danger layui-btn-xs" data-href="{:url('delCustomer')}" lay-event="del">{:lang('del')}</a>
                                </div>
                            </td>

                            <td rowspan="${rowSpan}" data-field="id" data-key="1-0-17" class="">
                                <div class="layui-table-cell laytable-cell-1-0-17">${mainRow.notes?mainRow.notes: ''}</div>
                            </td>
                        </tr>
                    `;
                    $tbody.append(mainTr);

                    // 插入子行（从第二个sku开始）
                    if (mainRow.sku.length > 1) {
                        mainRow.sku.slice(1).forEach((childRow) => {
                            var childTr = `
                                <tr class="child-row">
                                    <td>${childRow.num}${mainRow.unit}</td>
                                    <td>${childRow.price}</td>
                                    <td>${childRow.shipping_fee}</td>
                                    <td>${childRow.num}${mainRow.unit} / ${Number(childRow.num) * Number(childRow.price) + Number(childRow.shipping_fee)}</td>
                                </tr>
                            `;
                            $tbody.append(childTr);
                        });
                    }
                });
            }
        });


        $('#importExcel').on('click', function(){
            layer.open({
                type: 1,
                title: '导入Excel',
                area: ['400px', '200px'],
                content: `
                    <div class="layui-form" style="padding: 20px;">
                        <div class="layui-form-item">
                            <div class="layui-upload">
                                <button type="button" class="layui-btn" id="uploadExcel">选择文件</button>
                                <div class="layui-upload-list">
                                    <p id="uploadFileName"></p>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <button type="button" class="layui-btn layui-btn-normal" id="submitImport">开始导入</button>
                        </div>
                    </div>
                `,
                success: function(layero, index){
                    var uploadInst = upload.render({
                        elem: '#uploadExcel',
                        url: 'importExcel',
                        accept: 'file',
                        exts: 'xlsx|xls',
                        before: function(obj){
                            layer.load();
                        },
                        done: function(res){
                            layer.closeAll('loading');
                            if(res.code === 0){
                                layer.msg('上传成功', {icon: 1});
                                $('#uploadFileName').text(res.data.filename);
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        },
                        error: function(){
                            layer.closeAll('loading');
                            layer.msg('上传失败', {icon: 2});
                        }
                    });

                    // 提交导入
                    $('#submitImport').on('click', function(){
                        var filename = $('#uploadFileName').text();
                        if(!filename){
                            layer.msg('请先选择文件', {icon: 2});
                            return;
                        }
                        layer.confirm('确定要导入数据吗？', function(index){
                            layer.close(index);
                            layer.load();
                            $.post('importExcel', {filename: filename}, function(res){
                                layer.closeAll('loading');
                                if(res.code === 0){
                                    layer.msg('导入成功', {icon: 1});
                                    layer.closeAll();
                                    tableIn.reload();
                                } else {
                                    layer.msg(res.msg, {icon: 2});
                                }
                            });
                        });
                    });
                }
            });
        });


        // 搜索逻辑
        $('#search').click(function() {
            table.reload('list', {
                page: { curr: 1 },
                where: { keys: $('#keys').val() }
            });
        });
    });
</script>